package com.xincheng.shuimalong.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.io.File;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by xiaote on 2017/7/5.
 */

public class UploadImageActivity extends BaseActivity {
    @BindView(R.id.upload_tv1)
    TextView mUploadTv1;
    @BindView(R.id.upload_iv1)
    ImageView mUploadIv1;
    @BindView(R.id.upload_clear_iv1)
    ImageView mUploadClearIv1;
    @BindView(R.id.upload_tv2)
    TextView mUploadTv2;
    @BindView(R.id.upload_iv2)
    ImageView mUploadIv2;
    @BindView(R.id.upload_clear_iv2)
    ImageView mUploadClearIv2;
    @BindView(R.id.upload_msg_tv1)
    TextView mUploadMsgTv1;
    @BindView(R.id.upload_msg_tv2)
    TextView mUploadMsgTv2;
    @BindView(R.id.upload_layout1)
    FrameLayout mUploadLayout1;
    @BindView(R.id.upload_layout2)
    FrameLayout mUploadLayout2;
    @BindView(R.id.upload_image_hint_tv)
    TextView mHintTv;
    @BindView(R.id.upload_image_save_tv)
    TextView mSaveTv;

    private String mUploadImgPath1 = "", mUploadImgPath2 = "";
    private int mFrom;
    private int mBidId;
    private File mTempFile1, mTempFile2;
    private String mToken;

    private AlertView mPhotoAlert;
    private int mPhotoStatus;
    private String mUploadData1, mUploadData2;
    private boolean mUploadFromInfo;
    private boolean mCanUpdate;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_upload_image;
    }

    @Override
    public void initData() {
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        mFrom = extras.getInt(IntentKey.FROM);
        mBidId = extras.getInt(IntentKey.BID_ID, 0);
        mCanUpdate = extras.getBoolean(IntentKey.CAN_UPDATE, true);
        mUploadLayout1.setEnabled(mCanUpdate);
        mUploadLayout2.setEnabled(mCanUpdate);
        mUploadTv1.setVisibility(mCanUpdate ? View.VISIBLE : View.GONE);
        mUploadTv2.setVisibility(mCanUpdate ? View.VISIBLE : View.GONE);
        switch (mFrom) {
            case 1:
                mUploadFromInfo = extras.getBoolean(IntentKey.UPLOAD_FROM_FILL_INFO, false);
                initTitleBar(getString(R.string.car_owner_msg));
                if (mCanUpdate) {
                    mHintTv.setVisibility(View.VISIBLE);
                    mSaveTv.setVisibility(View.VISIBLE);
                }
                mUploadMsgTv1.setText(getString(R.string.idcard_front));
                mUploadMsgTv2.setText(getString(R.string.idcard_contrary));
                break;
            case 2:
                mUploadFromInfo = extras.getBoolean(IntentKey.UPLOAD_FROM_FILL_INFO, false);
                initTitleBar(getString(R.string.car_msg));
                if (mCanUpdate) {
                    mSaveTv.setVisibility(View.VISIBLE);
                }
                mUploadMsgTv1.setText(getString(R.string.driving_license_original));
                mUploadMsgTv2.setText(getString(R.string.driving_license_transcript));
                break;
            case 3:
                initTitleBar(getString(R.string.upload_guarantee));
                mSaveTv.setVisibility(View.VISIBLE);
                mUploadMsgTv1.setText(getString(R.string.vci_guarantee));
                mUploadMsgTv2.setText(getString(R.string.tci_guarantee));
                break;
        }
        mUploadImgPath1 = extras.getString(IntentKey.UPLOAD_IMG_PATH1);
        mUploadImgPath2 = extras.getString(IntentKey.UPLOAD_IMG_PATH2);
        mUploadData1=extras.getString(IntentKey.UPLOAD_IMG_BASE641);
        mUploadData2=extras.getString(IntentKey.UPLOAD_IMG_BASE642);
        if (!CommonUtil.isEmpty(mUploadImgPath1)) {
            showUploadImage1();
        }else if(!CommonUtil.isEmpty(mUploadData1)){
            showBaseImage1();
        }
        if (!CommonUtil.isEmpty(mUploadImgPath2)) {
            showUploadImage2();
        }else if(!CommonUtil.isEmpty(mUploadData2)){
            showBaseImage2();
        }
    }

    private void initAlertView() {
        mPhotoAlert = new AlertView(this, null, null, getString(R.string.cancel), null, Constant.CAMERA_OR_LOCAL,
                AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0:
                        photoCamera();
                        break;
                    case 1:
                        photoLocal();
                        break;
                }
            }
        });
    }

    @OnClick({R.id.upload_layout1, R.id.upload_layout2, R.id.upload_clear_iv1, R.id.upload_clear_iv2,
            R.id.upload_image_save_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.upload_layout1: {
                if (CommonUtil.isEmpty(mUploadImgPath1)) {
                    mPhotoStatus = 1;
                    initAlertView();
                    if (mPhotoAlert != null) {
                        mPhotoAlert.show();
                    }
                }
            }
            break;
            case R.id.upload_layout2: {
                if (CommonUtil.isEmpty(mUploadImgPath2)) {
                    mPhotoStatus = 2;
                    initAlertView();
                    if (mPhotoAlert != null) {
                        mPhotoAlert.show();
                    }
                }
            }
            break;
            case R.id.upload_clear_iv1: {
                mUploadImgPath1 = "";
                mUploadData1 = "";
                mUploadIv1.setVisibility(View.GONE);
                mUploadClearIv1.setVisibility(View.GONE);
                mUploadTv1.setVisibility(View.VISIBLE);
            }
            break;
            case R.id.upload_clear_iv2: {
                mUploadImgPath2 = "";
                mUploadData2 = "";
                mUploadIv2.setVisibility(View.GONE);
                mUploadClearIv2.setVisibility(View.GONE);
                mUploadTv2.setVisibility(View.VISIBLE);
            }
            break;
            case R.id.upload_image_save_tv:
                saveImage();
                break;
        }
    }

    private void photoCamera() {
        switch (mFrom) {
            case 1:
            case 2:
                switch (mPhotoStatus) {
                    case 1: {
                        XLog.e("openCamera");
                        Bundle extras = new Bundle();
                        extras.putInt(IntentKey.FROM, mFrom);
                        ShowActivity.showActivityForResult(getContext(), IdCardCameraActivity.class, extras,
                                RequestCodeKey.INDENTIFY_FRONT);
                    }
                    break;
                    case 2: {
                        XLog.e("openCamera");
                        Bundle extras = new Bundle();
                        extras.putInt(IntentKey.FROM, mFrom);
                        ShowActivity.showActivityForResult(this, IdCardCameraActivity.class, extras,
                                RequestCodeKey.INDENTIFY_CONTRARY);
                    }
                    break;
                }

                break;
            case 3:
                switch (mPhotoStatus) {
                    case 1: {
                        mTempFile1 = MyUtil.getOutputMediaFile(this, Constant.ID_CARD_PATH, "guarantee_vci_");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile1));
                        startActivityForResult(intent, RequestCodeKey.INDENTIFY_FRONT);
                    }
                    break;
                    case 2: {
                        mTempFile2 = MyUtil.getOutputMediaFile(this, Constant.ID_CARD_PATH, "guarantee_tci_");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定调用相机拍照后照片的储存路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile2));
                        startActivityForResult(intent, RequestCodeKey.INDENTIFY_CONTRARY);
                    }
                    break;
                }

                break;
        }
    }

    private void photoLocal() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择一张图片"),
                    RequestCodeKey.TAKE_PHOTO_LOCAL);
        } catch (Exception e) {
            CommonUtil.showToast(this, "请安装文件管理器");
        }
    }

    private void showUploadImage1() {
        mUploadTv1.setVisibility(View.GONE);
        mUploadIv1.setVisibility(View.VISIBLE);
        mUploadClearIv1.setVisibility(mCanUpdate ? View.VISIBLE : View.GONE);
        if (mFrom == 3) {
            Glide.with(this).load(mUploadImgPath1).into(mUploadIv1);
        } else {
            Glide.with(this).asBitmap().load(mUploadImgPath1).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = resource;
                    if (resource != null && resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                        bitmap = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                    }
                    mUploadIv1.setImageBitmap(bitmap);
                    mUploadData1 = BitmapUtil.bitmapToBase64(bitmap);
                }

            });
        }
    }
    private void showBaseImage1() {
        mUploadTv1.setVisibility(View.GONE);
        mUploadIv1.setVisibility(View.VISIBLE);
        mUploadClearIv1.setVisibility(View.VISIBLE);
        Bitmap bitmap = BitmapUtil.base64ToBitmap(mUploadImgPath1);
        mUploadIv1.setImageBitmap(bitmap);
    }
    private void showBaseImage2() {
        mUploadTv2.setVisibility(View.GONE);
        mUploadIv2.setVisibility(View.VISIBLE);
        mUploadClearIv2.setVisibility(View.VISIBLE);
        Bitmap bitmap = BitmapUtil.base64ToBitmap(mUploadImgPath2);
        mUploadIv2.setImageBitmap(bitmap);
    }
    private void showUploadImage2() {
        mUploadTv2.setVisibility(View.GONE);
        mUploadIv2.setVisibility(View.VISIBLE);
        mUploadClearIv2.setVisibility(mCanUpdate ? View.VISIBLE : View.GONE);
        if (mFrom == 3) {
            Glide.with(this).load(mUploadImgPath2).into(mUploadIv2);
        } else {
            Glide.with(this).asBitmap().load(mUploadImgPath2).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = resource;
                    if (resource != null && resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                        bitmap = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                    }
                    mUploadIv2.setImageBitmap(bitmap);
                    mUploadData2 = BitmapUtil.bitmapToBase64(bitmap);
                }


            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case Constant.CAMERA_SUCESS:
                switch (requestCode) {
                    case RequestCodeKey.INDENTIFY_FRONT:
                        //身份证正面
                        if (data != null && data.getData() != null) {
                            mUploadImgPath1 = data.getData().getPath();
                            showUploadImage1();
                        }
                        break;
                    case RequestCodeKey.INDENTIFY_CONTRARY:
                        //身份证反面
                        if (data != null && data.getData() != null) {
                            mUploadImgPath2 = data.getData().getPath();
                            showUploadImage2();
                        }
                        break;
                }
                break;
            case RESULT_OK:
                switch (requestCode) {
                    case RequestCodeKey.INDENTIFY_FRONT:
                        if (mTempFile1 != null && mTempFile1.exists()) {
                            mUploadImgPath1 = mTempFile1.getAbsolutePath();
                            showUploadImage1();
                        }
                        break;
                    case RequestCodeKey.INDENTIFY_CONTRARY:
                        if (mTempFile2 != null && mTempFile2.exists()) {
                            mUploadImgPath2 = mTempFile2.getAbsolutePath();
                            showUploadImage2();
                        }
                        break;
                    case RequestCodeKey.TAKE_PHOTO_LOCAL:
                        if (data != null && data.getData() != null) {
                            Uri uri = data.getData();
                            switch (mPhotoStatus) {
                                case 1:
                                    mUploadImgPath1 = CommonUtil.getLocalImagePath(this, uri);
                                    showUploadImage1();
                                    break;
                                case 2:
                                    mUploadImgPath2 = CommonUtil.getLocalImagePath(this, uri);
                                    showUploadImage2();
                                    break;
                            }
                        }
                        break;
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void addListener() {

    }

    public void saveImage() {
        if (CommonUtil.isEmpty(mUploadImgPath1) && CommonUtil.isEmpty(mUploadImgPath2)) {
            showToast("图片未编辑不能保存");
            return;
        }
        if (mFrom == 3) {
            Intent intent = new Intent();
            intent.putExtra(IntentKey.UPLOAD_IMG_PATH1, mUploadImgPath1);
            intent.putExtra(IntentKey.UPLOAD_IMG_PATH2, mUploadImgPath2);
            setResult(RESULT_OK, intent);
            finish();
            return;
        }
        Map<String, String> paramsMap = null;
        switch (mFrom) {
            case 1:
                if (mUploadFromInfo) {
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.UPLOAD_IMG_PATH1, mUploadImgPath1);
                    intent.putExtra(IntentKey.UPLOAD_IMG_PATH2, mUploadImgPath2);
                    setResult(RESULT_OK, intent);
                    finish();
                    return;
                }
                paramsMap = PostParam.editBill(mToken, mBidId, mUploadData1, mUploadData2, "", "");
                break;
            case 2:
                if (mUploadFromInfo) {
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.UPLOAD_IMG_PATH1, mUploadImgPath1);
                    intent.putExtra(IntentKey.UPLOAD_IMG_PATH2, mUploadImgPath2);
                    setResult(RESULT_OK, intent);
                    finish();
                    return;
                }
                paramsMap = PostParam.editBill(mToken, mBidId, "", "", mUploadData1, mUploadData2);
                break;
        }
        RetroSubscrube.getInstance().postSubscrube(AppUrl.EDIT_BILL, paramsMap,
                new BaseObserver(this, getString(R.string.loading_save)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast("上传成功");
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.SUCCESS, true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    public void back(View view) {
        finish();
    }

}
